/*
 * Xvidmode.c: get/set X video modes
 *
 * Copyright (C) 1999 by Ruda Moura
 */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <X11/Xlib.h>
#include <X11/extensions/xf86vmode.h>
#include "msg.h"

#define NEXT_MODE     +1
#define PREVIOUS_MODE -1

Display *Dpy;
XF86VidModeModeInfo **VmModeInfo;

void opendisplay()
{
	if ((Dpy = XOpenDisplay("")) == NULL)
		perr("can't open display");
}

void getcurrentmode()
{
	int vm_max;
	
	opendisplay();

	XF86VidModeGetAllModeLines(Dpy, XDefaultScreen(Dpy), \
				   &vm_max, &VmModeInfo);

	printf("%i %i\n", VmModeInfo[0]->hdisplay, \
			  VmModeInfo[0]->vdisplay);
}

void getallmodes()
{
	int i, vm_max;

	opendisplay();
	  
	XF86VidModeGetAllModeLines(Dpy, XDefaultScreen(Dpy), \
				   &vm_max, &VmModeInfo);

	for(i=0; i<vm_max; i++)
		printf("%i %i\n", VmModeInfo[i]->hdisplay, \
				  VmModeInfo[i]->vdisplay);
}

void setmode(int hres, int vres)
{
	int i, vm_max;
	
	opendisplay();

	XF86VidModeGetAllModeLines(Dpy, XDefaultScreen(Dpy), \
				   &vm_max, &VmModeInfo);
	
	for(i=0; i<vm_max; i++)
		if ((VmModeInfo[i]->hdisplay == hres) && \
		    (VmModeInfo[i]->vdisplay == vres)) {
			XF86VidModeSwitchToMode(Dpy, XDefaultScreen(Dpy), \
						VmModeInfo[i]);
			XFlush(Dpy);
			return;
		}

	perr("invalid mode");
}

void setzoommode(int zoom)
{
	opendisplay();

	XF86VidModeSwitchMode(Dpy, XDefaultScreen(Dpy), zoom);
	XFlush(Dpy);
}

int main(int argc, char *argv[])
{
	int hres, vres;

	switch (argc) {
	case 1:
		getcurrentmode();
		break;
	case 2:
		if (!strcmp(argv[1], "-h") || \
		    !strcmp(argv[1], "--help"))
			usage();
		else if (!strcmp(argv[1], "-l") || \
			 !strcmp(argv[1], "--listall"))
			getallmodes();
		else if (!strcmp(argv[1], "-n") || \
		 	 !strcmp(argv[1], "--next"))
			setzoommode(NEXT_MODE);
		else if (!strcmp(argv[1], "-p") || \
		 	 !strcmp(argv[1], "--previous"))
			setzoommode(PREVIOUS_MODE);
		else if (!strcmp(argv[1], "-v") || \
			 !strcmp(argv[1], "--version"))
			version();
		else
			usage();
		break;
	case 3:
		hres = atoi(argv[1]);
		vres = atoi(argv[2]);
		setmode(hres, vres);
		break;
	default:
		usage();
		break;
	}

	exit(0);
}
